<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="queryParams" ref="queryFormRef">
        <el-form-item label="设备名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入设备名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <!-- <el-form-item label="设备类型" prop="type">
					<el-select
						v-model="queryParams.type"
						placeholder="请选择设备类型"
						clearable
					>
						<el-option
							v-for="item in equipmentTypes"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						/>
					</el-select>
				</el-form-item> -->
        <el-form-item label="设备状态" prop="status">
          <el-select
            v-model="queryParams.isOperational"
            placeholder="请选择设备状态"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in equipmentStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <el-button type="primary" :icon="Plus" @click="handleAdd"
            >新增设备</el-button
          >
          <!-- <el-button type="warning" :icon="Tools" @click="handleMaintenance"
						>维护记录</el-button
					> -->
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="equipmentList"
        border
        style="width: 100%"
      >
        <el-table-column
          prop="name"
          label="设备名称"
          min-width="150"
          show-overflow-tooltip
        />
        <!-- <el-table-column prop="type" label="设备类型" width="120">
					<template #default="{ row }">
						{{ getEquipmentTypeLabel(row.type) }}
					</template>
				</el-table-column> -->
        <el-table-column
          prop="location"
          label="安装位置"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column prop="createdAt" label="购入日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="最近维护" width="120">
          <template #default="{ row }">
            {{ formatDate(row.updatedAt) }}
          </template>
        </el-table-column>
        <!-- <el-table-column
					prop="nextMaintenanceDate"
					label="下次维护"
					width="120"
				>
					<template #default="{ row }">
						{{ formatDate(row.nextMaintenanceDate) }}
					</template>
				</el-table-column> -->
        <el-table-column
          prop="isOperational"
          label="设备状态"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.isOperational)">
              {{ getEquipmentStatusLabel(row.isOperational) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              :icon="Edit"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <!-- <el-button
              type="success"
              link
              :icon="Tools"
              @click="handleAddMaintenance(row)"
            >
              添加维护
            </el-button> -->
            <el-button
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNumber"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 设备表单对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.type === 'add' ? '新增设备' : '编辑设备'"
      width="600px"
    >
      <el-form
        ref="dialogFormRef"
        :model="dialog.form"
        :rules="dialog.rules"
        label-width="100px"
      >
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="dialog.form.name" placeholder="请输入设备名称" />
        </el-form-item>
        <!-- <el-form-item label="设备类型" prop="type">
					<el-select
						v-model="dialog.form.type"
						placeholder="请选择设备类型"
						style="width: 100%"
					>
						<el-option
							v-for="item in equipmentTypes"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						/>
					</el-select>
				</el-form-item> -->
        <el-form-item label="安装位置" prop="location">
          <el-input
            v-model="dialog.form.location"
            placeholder="请输入安装位置"
          />
        </el-form-item>
        <el-form-item label="购入日期" prop="createdAt">
          <el-date-picker
            v-model="dialog.form.createdAt"
            type="date"
            placeholder="选择购入日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="设备状态" prop="isOperational">
          <el-select
            v-model="dialog.form.isOperational"
            placeholder="请选择设备状态"
            style="width: 100px"
          >
            <el-option
              v-for="item in equipmentStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="备注" prop="remark">
					<el-input
						v-model="dialog.form.remark"
						type="textarea"
						placeholder="请输入备注信息"
						:rows="3"
					/>
				</el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 维护记录对话框 -->
    <el-dialog
      v-model="maintenanceDialog.visible"
      :title="maintenanceDialog.type === 'list' ? '维护记录' : '添加维护记录'"
      width="700px"
    >
      <template v-if="maintenanceDialog.type === 'list'">
        <el-table :data="maintenanceDialog.records" border style="width: 100%">
          <el-table-column
            prop="equipmentName"
            label="设备名称"
            min-width="150"
          />
          <el-table-column prop="maintenanceDate" label="维护日期" width="120">
            <template #default="{ row }">
              {{ formatDate(row.maintenanceDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="maintenanceType" label="维护类型" width="100">
            <template #default="{ row }">
              <el-tag
                :type="
                  row.maintenanceType === 'Regular' ? 'primary' : 'warning'
                "
              >
                {{ row.maintenanceType === "Regular" ? "常规" : "故障" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="description"
            label="维护内容"
            min-width="200"
            show-overflow-tooltip
          />
          <el-table-column prop="maintainer" label="维护人员" width="120" />
        </el-table>
      </template>
      <template v-else>
        <el-form
          ref="maintenanceFormRef"
          :model="maintenanceDialog.form"
          :rules="maintenanceDialog.rules"
          label-width="100px"
        >
          <el-form-item label="维护日期" prop="maintenanceDate">
            <el-date-picker
              v-model="maintenanceDialog.form.maintenanceDate"
              type="date"
              placeholder="选择维护日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <!-- <el-form-item label="维护类型" prop="maintenanceType">
						<el-radio-group v-model="maintenanceDialog.form.maintenanceType">
							<el-radio label="Regular">常规维护</el-radio>
							<el-radio label="Repair">故障维修</el-radio>
						</el-radio-group>
					</el-form-item> -->
          <el-form-item label="维护内容" prop="description">
            <el-input
              v-model="maintenanceDialog.form.description"
              type="textarea"
              :rows="3"
              placeholder="请输入维护内容"
            />
          </el-form-item>
          <el-form-item label="维护人员" prop="maintainer">
            <el-input
              v-model="maintenanceDialog.form.maintainer"
              placeholder="请输入维护人员"
            />
          </el-form-item>
          <!-- <el-form-item label="下次维护" prop="nextMaintenanceDate">
						<el-date-picker
							v-model="maintenanceDialog.form.nextMaintenanceDate"
							type="date"
							placeholder="选择下次维护日期"
							style="width: 100%"
							value-format="YYYY-MM-DD"
						/>
					</el-form-item> -->
        </el-form>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="maintenanceDialog.visible = false">
            {{ maintenanceDialog.type === "list" ? "关闭" : "取消" }}
          </el-button>
          <el-button
            v-if="maintenanceDialog.type === 'add'"
            type="primary"
            @click="handleMaintenanceSubmit"
          >
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Refresh,
  Plus,
  Edit,
  Delete,
  Tools,
} from "@element-plus/icons-vue";
import {
  getEquipments,
  createEquipment,
  updateEquipment,
  deleteEquipment,
  getMaintenanceRecords,
  addMaintenanceRecord,
} from "@/api/property";

// 设备类型选项
const equipmentTypes = [
  { label: "电梯", value: "Elevator" },
  { label: "消防设备", value: "FireFighting" },
  { label: "监控设备", value: "Surveillance" },
  { label: "供水设备", value: "WaterSupply" },
  { label: "供电设备", value: "PowerSupply" },
  { label: "其他", value: "Other" },
];

// 设备状态选项
const equipmentStatus = [
  { label: "正常", value: true },
  { label: "维护", value: false },
];

// 查询参数
const queryParams = ref({
  name: "",
  type: "",
  isOperational: "",
  pageNumber: 1,
  pageSize: 10,
});

// 数据相关
const loading = ref(false);
const equipmentList = ref([]);
const total = ref(0);
const queryFormRef = ref();

// 设备表单对话框
const dialog = reactive({
  visible: false,
  type: "add",
  form: {
    name: "",
    type: "",
    location: "",
    createdAt: "",
    status: "Normal",
    remark: "",
  },
  rules: {
    name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
    type: [{ required: true, message: "请选择设备类型", trigger: "change" }],
    location: [{ required: true, message: "请输入安装位置", trigger: "blur" }],
    createdAt: [
      { required: true, message: "请选择购入日期", trigger: "change" },
    ],
    isOperational: [
      { required: true, message: "请选择设备状态", trigger: "change" },
    ],
  },
});

// 维护记录对话框
const maintenanceDialog = reactive({
  visible: false,
  type: "list",
  records: [],
  currentEquipment: null,
  form: {
    maintenanceDate: "",
    maintenanceType: "Regular",
    description: "",
    maintainer: "",
    nextMaintenanceDate: "",
  },
  rules: {
    maintenanceDate: [
      { required: true, message: "请选择维护日期", trigger: "change" },
    ],
    maintenanceType: [
      { required: true, message: "请选择维护类型", trigger: "change" },
    ],
    description: [
      { required: true, message: "请输入维护内容", trigger: "blur" },
    ],
    maintainer: [
      { required: true, message: "请输入维护人员", trigger: "blur" },
    ],
    // nextMaintenanceDate: [
    // 	{ required: true, message: "请选择下次维护日期", trigger: "change" },
    // ],
  },
});

// 获取设备列表
const getList = async () => {
  try {
    loading.value = true;
    const res = await getEquipments(queryParams.value);
    equipmentList.value = res.items;
    total.value = res.total;
  } catch (error) {
    console.error("获取设备列表失败：", error);
  } finally {
    loading.value = false;
  }
};

// 搜索方法
const handleQuery = () => {
  queryParams.value.pageNumber = 1;
  getList();
};

// 重置搜索
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

// 新增设备
const handleAdd = () => {
  dialog.type = "add";
  dialog.form = {
    name: "",
    location: "",
    createdAt: "",
    isOperational: true,
    remark: "",
  };
  dialog.visible = true;
};

// 编辑设备
const handleEdit = (row) => {
  dialog.type = "edit";
  dialog.form = { ...row };
  dialog.visible = true;
};

// 删除设备
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该设备吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await deleteEquipment(row.id);
      ElMessage.success("删除成功");
      getList();
    } catch (error) {
      console.error("删除失败：", error);
    }
  });
};

// 提交设备表单
const handleSubmit = async () => {
  try {
    if (dialog.type === "add") {
      await createEquipment(dialog.form);
      ElMessage.success("创建成功");
    } else {
      await updateEquipment(dialog.form.id, dialog.form);
      ElMessage.success("更新成功");
    }
    dialog.visible = false;
    getList();
  } catch (error) {
    console.error("保存失败：", error);
  }
};

// 查看维护记录
const handleMaintenance = async () => {
  try {
    maintenanceDialog.type = "list";
    maintenanceDialog.visible = true;
    const res = await getMaintenanceRecords();
    maintenanceDialog.records = res.items;
  } catch (error) {
    console.error("获取维护记录失败：", error);
  }
};

// 添加维护记录
const handleAddMaintenance = (row) => {
  // maintenanceDialog.type = "add";
  // maintenanceDialog.currentEquipment = row;
  // maintenanceDialog.form = {
  // 	maintenanceDate: "",
  // 	maintenanceType: "Regular",
  // 	description: "",
  // 	maintainer: "",
  // 	nextMaintenanceDate: "",
  // };
  // maintenanceDialog.visible = true;
  ElMessageBox.confirm("确定要添加维护吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await addMaintenanceRecord(row.id);
    ElMessage.success("操作成功");
    getList();
  });
};

// 提交维护记录
const handleMaintenanceSubmit = async () => {
  try {
    await addMaintenanceRecord(
      maintenanceDialog.currentEquipment.id,
      maintenanceDialog.form
    );
    ElMessage.success("添加维护记录成功");
    maintenanceDialog.visible = false;
    getList();
  } catch (error) {
    console.error("添加维护记录失败：", error);
  }
};

// 分页方法
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val;
  getList();
};

const handleCurrentChange = (val) => {
  queryParams.value.pageNumber = val;
  getList();
};

// 获取设备类型标签
const getEquipmentTypeLabel = (type) => {
  return equipmentTypes.find((item) => item.value === type)?.label || type;
};

// 获取设备状态标签
const getEquipmentStatusLabel = (status) => {
  return equipmentStatus.find((item) => item.value === status)?.label || status;
};

// 获取状态标签类型
const getStatusType = (status) => {
  if (status) {
    return "success";
  } else {
    return "warning";
  }
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return "-";
  return new Date(date).toLocaleDateString();
};

// 初始化
onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
